package lib.quasar.widget.image;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.StateListDrawable;
import android.support.v7.widget.AppCompatImageView;
import android.util.AttributeSet;

import lib.quasar.widget.R;

/**
 * description: 按压背景，边框变色
 * created by kalu on 2016/11/26 11:29
 */
public class StateImageView extends AppCompatImageView {

    private final StateListDrawable mStateBackground = new StateListDrawable();
    private final GradientDrawable mNormalBackground = new GradientDrawable();
    private final GradientDrawable mPressedBackground = new GradientDrawable();
    private final GradientDrawable mUnableBackground = new GradientDrawable();
    private final int[][] mState = new int[][]{
            new int[]{android.R.attr.state_pressed, android.R.attr.state_enabled},
            new int[]{android.R.attr.state_enabled, android.R.attr.state_focused},
            new int[]{android.R.attr.state_enabled},
            new int[]{android.R.attr.state_window_focused}
    };

    /****************************/

    public StateImageView(Context context) {
        this(context, null);
    }

    public StateImageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public StateImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setClickable(true);

        //获取所有的自定义属性
        TypedArray a = null;
        try {
            a = context.obtainStyledAttributes(attrs, R.styleable.StateImageView);
            final int color1 = a.getColor(R.styleable.StateImageView_siv_bg_color_normal, Color.TRANSPARENT);
            mNormalBackground.setColor(color1);
            final int color2 = a.getColor(R.styleable.StateImageView_siv_bg_color_press, Color.TRANSPARENT);
            mPressedBackground.setColor(color2);
            final int color3 = a.getColor(R.styleable.StateImageView_siv_bg_color_unable, Color.TRANSPARENT);
            mUnableBackground.setColor(color3);
        } catch (Exception e) {
        } finally {
            if (null != a) {
                a.recycle();
            }
        }

        mStateBackground.addState(mState[0], mPressedBackground);
        mStateBackground.addState(mState[1], mPressedBackground);
        mStateBackground.addState(mState[2], mNormalBackground);
        mStateBackground.addState(mState[3], mUnableBackground);
        setBackgroundDrawable(mStateBackground);
    }
}
